package ThreadDemo;

/*
 * Author: JacksonCoder
 * FileName: FutureCode
 * Version: 1.0.0
 * Date: 2025/2/21
 */

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

public class FutureCode {

    public static void printFuture() throws ExecutionException, InterruptedException {
        ExecutorService executor = Executors.newSingleThreadExecutor();

        // 提交一个Callable任务
        Future<String> future = executor.submit(() -> {
            Thread.sleep(2000);
            return "hello from future!";
        });


        // master thread continue to do other things
        System.out.println("Doing other things...");

        // 获取异步任务的结果（阻塞直到任务完成）
        String result = future.get();
        System.out.println(result);

        // close ExecutorService
        executor.shutdown();

    }

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        printFuture();
    }

}
